package com.ruoyi.point.service.impl;

import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;
import com.ruoyi.point.mapper.MallGoodsMapper;
import com.ruoyi.point.domain.MallGoods;
import com.ruoyi.point.service.IMallGoodsService;

/**
 * 积分商城商品Service业务层处理
 * 
 * @author hy
 * @date 2025-08-12
 */
@Service
public class MallGoodsServiceImpl implements IMallGoodsService 
{
    @Autowired
    private MallGoodsMapper mallGoodsMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 缓存常量
    private static final String MALL_GOODS_DETAIL_KEY = "mall_goods:detail:";
    private static final String MALL_GOODS_LIST_KEY = "mall_goods:list:";
    private static final String MALL_GOODS_HOT_KEY = "mall_goods:hot";
    private static final String MALL_GOODS_HOT_SALES_KEY = "mall_goods:hot:sales";
    private static final String MALL_GOODS_NEW_TIME_KEY = "mall_goods:new:time";
    private static final String MALL_GOODS_RECOMMENDED_KEY = "mall_goods:recommended";
    private static final Duration MALL_GOODS_DETAIL_EXPIRE = Duration.ofMinutes(30);
    private static final Duration MALL_GOODS_LIST_EXPIRE = Duration.ofMinutes(15);
    private static final Duration MALL_GOODS_CACHE_EXPIRE = Duration.ofMinutes(10);
    private static final Duration MALL_GOODS_HOT_SALES_EXPIRE = Duration.ofMinutes(20);
    private static final Duration MALL_GOODS_NEW_TIME_EXPIRE = Duration.ofMinutes(25);

    /**
     * 查询积分商城商品
     * 
     * @param id 积分商城商品主键
     * @return 积分商城商品
     */
    @Override
    public MallGoods selectMallGoodsById(Integer id)
    {
        return mallGoodsMapper.selectMallGoodsById(id);
    }

    /**
     * 查询积分商城商品列表
     * 
     * @param mallGoods 积分商城商品
     * @return 积分商城商品
     */
    @Override
    public List<MallGoods> selectMallGoodsList(MallGoods mallGoods)
    {
        return mallGoodsMapper.selectMallGoodsList(mallGoods);
    }

    /**
     * 新增积分商城商品
     * 
     * @param mallGoods 积分商城商品
     * @return 结果
     */
    @Override
    public int insertMallGoods(MallGoods mallGoods)
    {
        int result = mallGoodsMapper.insertMallGoods(mallGoods);
        if (result > 0) {
            // 清除相关缓存
            clearMallGoodsCache();
        }
        return result;
    }

    /**
     * 修改积分商城商品
     * 
     * @param mallGoods 积分商城商品
     * @return 结果
     */
    @Override
    public int updateMallGoods(MallGoods mallGoods)
    {
        int result = mallGoodsMapper.updateMallGoods(mallGoods);
        if (result > 0) {
            // 清除相关缓存
            clearMallGoodsCache();
            clearMallGoodsDetailCache(mallGoods.getId());
        }
        return result;
    }

    /**
     * 批量删除积分商城商品
     * 
     * @param ids 需要删除的积分商城商品主键集合
     * @return 结果
     */
    @Override
    public int deleteMallGoodsByIds(Integer[] ids)
    {
        int result = mallGoodsMapper.deleteMallGoodsByIds(ids);
        if (result > 0) {
            // 清除相关缓存
            clearMallGoodsCache();
            for (Integer id : ids) {
                clearMallGoodsDetailCache(id);
            }
        }
        return result;
    }

    /**
     * 删除积分商城商品信息
     * 
     * @param id 积分商城商品主键
     * @return 结果
     */
    @Override
    public int deleteMallGoodsById(Integer id)
    {
        int result = mallGoodsMapper.deleteMallGoodsById(id);
        if (result > 0) {
            clearMallGoodsDetailCache(id);
            clearMallGoodsCache();
        }
        return result;
    }

    /**
     * 根据ID查询商品详情（多表联查，包含规格信息）
     * 
     * @param id 商品ID
     * @return 商品详情
     */
    @Override
    public MallGoods selectMallGoodsDetailById(Integer id)
    {
        String cacheKey = MALL_GOODS_DETAIL_KEY + id;
        
        // 尝试从缓存获取
        MallGoods cached = (MallGoods) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        MallGoods result = mallGoodsMapper.selectMallGoodsDetailById(id);
        if (result != null) {
            // 确保规格信息正确加载
            if (result.getSpecifications() != null && !result.getSpecifications().isEmpty()) {
                // 规格信息已通过SQL联查获取，无需额外处理
                System.out.println("商品ID: " + id + " 加载规格数量: " + result.getSpecifications().size());
            } else {
                System.out.println("商品ID: " + id + " 未找到规格信息");
            }
            
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, MALL_GOODS_DETAIL_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询商品列表（多表联查，支持分页和筛选）
     * 
     * @param mallGoods 查询条件
     * @return 商品列表
     */
    @Override
    public List<MallGoods> selectMallGoodsListWithStats(MallGoods mallGoods)
    {
        String cacheKey = MALL_GOODS_LIST_KEY + mallGoods.hashCode();
        
        // 尝试从缓存获取
        List<MallGoods> cached = (List<MallGoods>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<MallGoods> result = mallGoodsMapper.selectMallGoodsListWithStats(mallGoods);
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(cacheKey, result, MALL_GOODS_LIST_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询热门商品列表
     * 
     * @return 热门商品列表
     */
    @Override
    public List<MallGoods> selectHotMallGoodsList()
    {
        // 尝试从缓存获取
        List<MallGoods> cached = (List<MallGoods>) redisTemplate.opsForValue().get(MALL_GOODS_HOT_KEY);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<MallGoods> result = mallGoodsMapper.selectHotMallGoodsList();
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(MALL_GOODS_HOT_KEY, result, MALL_GOODS_CACHE_EXPIRE);
        }
        
        return result;
    }

    /**
     * 查询热门商品列表（按销量排序）
     * 
     * @param limit 限制数量
     * @return 热门商品列表
     */
    @Override
    public List<MallGoods> selectHotMallGoodsListBySales(Integer limit)
    {
        if (limit == null || limit <= 0) {
            limit = 10; // 默认10个
        }
        
        // 尝试从Redis ZSet获取
        Set<Object> cachedIds = redisTemplate.opsForZSet().reverseRange(MALL_GOODS_HOT_SALES_KEY, 0, limit - 1);
        if (cachedIds != null && !cachedIds.isEmpty()) {
            // 从ZSet获取到商品ID，批量查询商品详情
            List<MallGoods> result = new ArrayList<>();
            for (Object id : cachedIds) {
                MallGoods goods = selectMallGoodsById((Integer) id);
                if (goods != null) {
                    result.add(goods);
                }
            }
            if (!result.isEmpty()) {
                System.out.println("从Redis ZSet缓存获取热门商品，数量: " + result.size());
                return result;
            }
        }
        
        // 从数据库查询并按销量排序
        List<MallGoods> result = mallGoodsMapper.selectHotMallGoodsListBySales(limit);
        if (result != null && !result.isEmpty()) {
            // 更新Redis ZSet缓存
            updateHotSalesCache(result);
            System.out.println("从数据库查询热门商品并更新缓存，数量: " + result.size());
        }
        
        return result;
    }

    /**
     * 查询新品列表（按创建时间排序）
     * 
     * @param limit 限制数量
     * @return 新品列表
     */
    @Override
    public List<MallGoods> selectNewMallGoodsListByTime(Integer limit)
    {
        if (limit == null || limit <= 0) {
            limit = 10; // 默认10个
        }
        
        // 尝试从Redis ZSet获取（按时间戳排序）
        Set<Object> cachedIds = redisTemplate.opsForZSet().reverseRange(MALL_GOODS_NEW_TIME_KEY, 0, limit - 1);
        if (cachedIds != null && !cachedIds.isEmpty()) {
            // 从ZSet获取到商品ID，批量查询商品详情
            List<MallGoods> result = new ArrayList<>();
            for (Object id : cachedIds) {
                MallGoods goods = selectMallGoodsById((Integer) id);
                if (goods != null) {
                    result.add(goods);
                }
            }
            if (!result.isEmpty()) {
                System.out.println("从Redis ZSet缓存获取新品，数量: " + result.size());
                return result;
            }
        }
        
        // 从数据库查询并按创建时间排序
        List<MallGoods> result = mallGoodsMapper.selectNewMallGoodsListByTime(limit);
        if (result != null && !result.isEmpty()) {
            // 更新Redis ZSet缓存
            updateNewTimeCache(result);
            System.out.println("从数据库查询新品并更新缓存，数量: " + result.size());
        }
        
        return result;
    }

    /**
     * 查询推荐商品列表
     * 
     * @return 推荐商品列表
     */
    @Override
    public List<MallGoods> selectRecommendedMallGoodsList()
    {
        // 尝试从缓存获取
        List<MallGoods> cached = (List<MallGoods>) redisTemplate.opsForValue().get(MALL_GOODS_RECOMMENDED_KEY);
        if (cached != null) {
            return cached;
        }
        
        // 从数据库查询
        List<MallGoods> result = mallGoodsMapper.selectRecommendedMallGoodsList();
        if (result != null && !result.isEmpty()) {
            // 存入缓存
            redisTemplate.opsForValue().set(MALL_GOODS_RECOMMENDED_KEY, result, MALL_GOODS_CACHE_EXPIRE);
        }
        
        return result;
    }

    /**
     * 清除商品详情缓存
     */
    private void clearMallGoodsDetailCache(Integer id) {
        redisTemplate.delete(MALL_GOODS_DETAIL_KEY + id);
    }

    /**
     * 更新热门商品销量缓存
     * 
     * @param goodsList 商品列表
     */
    private void updateHotSalesCache(List<MallGoods> goodsList) {
        if (goodsList == null || goodsList.isEmpty()) {
            return;
        }
        
        try {
            // 清空旧的ZSet缓存
            redisTemplate.delete(MALL_GOODS_HOT_SALES_KEY);
            
            // 将商品ID和销量添加到ZSet，销量作为分数
            for (MallGoods goods : goodsList) {
                if (goods.getId() != null && goods.getSales() != null) {
                    redisTemplate.opsForZSet().add(MALL_GOODS_HOT_SALES_KEY, goods.getId(), goods.getSales().doubleValue());
                }
            }
            
            // 设置ZSet缓存过期时间
            redisTemplate.expire(MALL_GOODS_HOT_SALES_KEY, MALL_GOODS_HOT_SALES_EXPIRE);
            
            System.out.println("Redis ZSet缓存更新成功，商品数量: " + goodsList.size());
        } catch (Exception e) {
            System.err.println("更新Redis ZSet缓存失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 更新新品时间缓存
     * 
     * @param goodsList 商品列表
     */
    private void updateNewTimeCache(List<MallGoods> goodsList) {
        if (goodsList == null || goodsList.isEmpty()) {
            return;
        }
        
        try {
            // 清空旧的ZSet缓存
            redisTemplate.delete(MALL_GOODS_NEW_TIME_KEY);
            
            // 将商品ID和创建时间添加到ZSet，创建时间作为分数
            for (MallGoods goods : goodsList) {
                if (goods.getId() != null && goods.getCreateTime() != null) {
                    redisTemplate.opsForZSet().add(MALL_GOODS_NEW_TIME_KEY, goods.getId(), goods.getCreateTime().getTime());
                }
            }
            
            // 设置ZSet缓存过期时间
            redisTemplate.expire(MALL_GOODS_NEW_TIME_KEY, MALL_GOODS_NEW_TIME_EXPIRE);
            
            System.out.println("Redis ZSet缓存更新成功，商品数量: " + goodsList.size());
        } catch (Exception e) {
            System.err.println("更新Redis ZSet缓存失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 清除商品列表缓存
     */
    private void clearMallGoodsCache() {
        redisTemplate.delete(MALL_GOODS_HOT_KEY);
        redisTemplate.delete(MALL_GOODS_HOT_SALES_KEY);
        redisTemplate.delete(MALL_GOODS_RECOMMENDED_KEY);
        redisTemplate.delete(MALL_GOODS_NEW_TIME_KEY); // 清除新品缓存
        // 清除所有列表缓存（这里可以根据实际需求优化）
        redisTemplate.delete(MALL_GOODS_LIST_KEY + "*");
    }

    /**
     * 更新商品库存和销量（兑换后）
     * 
     * @param goodsId 商品ID
     * @return 结果
     */
    @Override
    public int updateGoodsStockAndSales(Integer goodsId)
    {
        int result = mallGoodsMapper.updateGoodsStockAndSales(goodsId);
        if (result > 0) {
            // 清除相关缓存
            clearMallGoodsDetailCache(goodsId);
            clearMallGoodsCache();
        }
        return result;
    }
}
